package com.snoweagler.userdetails;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.Arrays;
import java.util.Map;

public class CustomUserDetailService implements UserDetailsService {

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
        String sql = "select * from sys_user where name = ?";
        Map<String, Object> objectMap = null;

        try {
            objectMap = jdbcTemplate.queryForMap(sql,name);
            User user = new User(objectMap.get("name").toString(), objectMap.get("password").toString(), Arrays.asList(new SimpleGrantedAuthority("ROLE_ADMIN")));
            return user;
        } catch (Exception e) {
            e.printStackTrace();
            throw new UsernameNotFoundException("账号或密码错误");
        }
    }
}
